import 'dart:developer';

import 'package:chewie/chewie.dart';
import 'package:extended_image/extended_image.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter/widgets.dart';
import 'package:get/get.dart';
import 'package:getx_learn/app/common/widgets/widgets.dart';
import 'package:getx_learn/app/modules/weichat_post/entity/index.dart';
import 'package:getx_learn/app/modules/weichat_post/modules/post/constant/config.dart';
import 'package:getx_learn/app/modules/weichat_post/styles/text.dart';
import 'package:getx_learn/app/modules/weichat_post/util/index.dart';
import 'package:getx_learn/app/modules/weichat_post/widgets/appbar.dart';
import 'package:getx_learn/app/modules/weichat_post/widgets/index.dart';
import 'package:getx_learn/global.dart';
import 'package:video_player/video_player.dart';
import 'package:wechat_assets_picker/wechat_assets_picker.dart';

enum GalleryType { assets, urls, video }

/// 图像浏览器
/// https://www.bilibili.com/video/BV1MM411h7kB/?spm_id_from=333.999.0.0&vd_source=e07cc8cc94eb22bd76722071b03cd199
class GalleryWidget extends StatefulWidget {
  const GalleryWidget(
      {super.key,
      required this.initialIndex,
      this.items,
      this.isBarVisible,
      this.timelineModel,
      this.imageUrls});

  // 初始图片的位置
  final int initialIndex;

  // 图片列表
  final List<AssetEntity>? items;

  /// URL 图片列表
  final List<String>? imageUrls;

  // 是否显示 bar
  final bool? isBarVisible;

  /// 动态信息
  final TimelineModel? timelineModel;

  @override
  State<GalleryWidget> createState() => _GalleryWidgetState();
}

///
/// SingleTickerProviderStateMixin : 动画的时候，可以混入，可以界面销毁的时候关闭动画
/// RouteAware : 路由监听
class _GalleryWidgetState extends State<GalleryWidget>
    with SingleTickerProviderStateMixin, WidgetsBindingObserver, RouteAware {
  bool visible = true;

  // 当前页码
  int _currentPage = 0;

  // 预览类型
  GalleryType _galleryType = GalleryType.assets;

  // 是否显示 bar
  bool _isShowAppBar = true;

  // video 视频控制器
  VideoPlayerController? _videoController;

  // chewie 控制器
  ChewieController? _chewieController;

  // 动画控制器
  late final AnimationController controller;

// 当系统将应用程序置于后台或返回时调用 应用程序到前台。
  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    super.didChangeAppLifecycleState(state);
    print("didChangeAppLifecycleState: ${state}");
    if (_videoController?.value.isInitialized != true) return;
    // 该应用程序当前对用户不可见，不响应 用户输入，并在后台运行。
    if (state != AppLifecycleState.paused) {
      _chewieController?.pause();
    }
    // 该应用程序是可见的并响应用户输入。
    if (state != AppLifecycleState.resumed) {
      _chewieController?.play();
    }
  }

  // 在此 【State】 对象的依赖项更改时调用
  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    // 订阅路由
    Global.routeObserver.subscribe(this, ModalRoute.of(context) as PageRoute);
  }

  @override
  void initState() {
    super.initState();

    // 当前页码
    _currentPage = widget.initialIndex + 1;

    // 阅览类型
    _galleryType = GalleryType.assets;
    // 视频
    if (widget.timelineModel?.postType == "2") {
      _galleryType = GalleryType.video;
    }
    // 发布选取的图片
    else if (widget.items != null) {
      _galleryType = GalleryType.assets;
    }

    // url 图片列表
    else if (widget.imageUrls != null) {
      _galleryType = GalleryType.urls;
    }

    visible = widget.isBarVisible ?? true;
    controller = AnimationController(
      vsync: this,
      duration: Duration(milliseconds: 400),
    );

    // 是否显示bar
    _isShowAppBar = widget.isBarVisible ?? true;

    // 将给定对象注册为绑定观察者（需要混入 WidgetsBindingObserver），捆绑 当各种应用程序事件发生时，
    // 当系统，
    WidgetsBinding.instance.addObserver(this);

    // 在下一帧之后调用回调，如果在帧绘制之前，则回调将在下一帧调用
    WidgetsBinding.instance.addPostFrameCallback((_) => _onLoadVideo());
  }

  @override
  Widget build(BuildContext context) {
    return _buildMainView();
  }

  @override
  void dispose() {
    WidgetsBinding.instance.removeObserver(this);
    _videoController?.dispose();
    _chewieController?.dispose();
    _videoController = null;
    _chewieController = null;
    Global.routeObserver.unsubscribe(this);
    super.dispose();
  }

// 当由 A 打开B页面时，B 页面调起该方法
  @override
  void didPush() {
    super.didPush();
    print("didPush");
  }

  // B页面打开c页面，B页面调起该方法
  @override
  void didPushNext() {
    super.didPushNext();
    print("didPushNext");
    if (_videoController?.value.isInitialized != true) return;
    _chewieController?.pause();
  }

  // B页面返回上一个页面时，B页面调起该方法
  @override
  void didPop() {
    super.didPop();
    
    print("didPop");
  }

// 当从B页面从c页面回来时，该方法被调起
  @override
  void didPopNext() {
    super.didPopNext();
    print("didPopNext");
    if (_videoController?.value.isInitialized != true) return;
    _chewieController?.play();
  }

  Widget _buildMainView() {
    // 默认加载中
    Widget body = const Text('loading');

    switch (_galleryType) {
      case GalleryType.assets:
        body = _buildAssetsImageView();
        break;
      case GalleryType.video:
        body = _buildVideoView();
        break;
      case GalleryType.urls:
        body = _buildUrlsImageView();
        break;
    }

    // // url 视频
    // if (widget.timelineModel?.postType == "2") {
    //   body = _buildVideoView();
    // }

    // // 发布获取的相册图片 AssetEntity
    // else if (widget.items?.isNotEmpty == true) {
    //   body = _buildImageView();
    // }

    // 数量
    int itemsCount = widget.items?.length ?? widget.imageUrls?.length ?? 0;

    return GestureDetector(
      // 防止透明区域事件穿透
      behavior: HitTestBehavior.opaque,
      onTap: () {
        // Navigator.pop(context);
        // Get.back();
        setState(() {
          _isShowAppBar = !_isShowAppBar;
        });
      },
      child: Scaffold(
        // 背景黑色
        backgroundColor: Colors.black,

        appBar: _galleryType == GalleryType.assets ? _buildPublishNav(itemsCount) : _buildPreviewNav(itemsCount),

        // appBar: AppBarWidget(
        //   isAnimated: true,
        //   isShow: _isShowAppBar,
        //   leading: GestureDetector(
        //     onTap: () => Navigator.pop(context),
        //     child: const Icon(
        //       Icons.arrow_back_ios_outlined,
        //       color: Colors.white,
        //     ),
        //   ),
        //   actions: [
        //     GestureDetector(
        //       onTap: () {
        //         // 导航压入新界面
        //         Navigator.push(context, MaterialPageRoute(builder: (context) {
        //           return Scaffold(
        //             appBar: AppBar(
        //               title: Text("新界面"),
        //             ),
        //             body: const Center(
        //               child: Text('新界面'),
        //             ),
        //           );
        //         }));
        //       },
        //       child: const Padding(
        //         padding: EdgeInsets.only(right: pagePadding),
        //         child: Icon(
        //           Icons.more_horiz_outlined,
        //           color: Colors.white,
        //         ),
        //       ),
        //     )
        //   ],
        // ),
        // 设置为 true，则内容可以撑开到 appBar 和状态栏的区域
        extendBodyBehindAppBar: true,
        // 视频，图片
        body: body,

        bottomSheet: _buildTimelineBar(_isShowAppBar),
      ),
    );

    // return GestureDetector(
    //   // 防止透明区域事件穿透
    //   behavior: HitTestBehavior.opaque,
    //   onTap: () {
    //     // Navigator.pop(context);
    //     // Get.back();
    //     setState(() {
    //       visible = !visible;
    //     });
    //   },
    //   child: Scaffold(
    //     appBar: SlideAppBarWidget(
    //       controller: controller,
    //       visible: visible,
    //       child: getAppBar(
    //         context: context,
    //         title: "图片浏览",
    //         backgroundColor: Colors.red.withOpacity(0.5),
    //       ),
    //     ),
    //     // 设置为 true，则内容可以撑开到 appBar 和状态栏的区域
    //     extendBodyBehindAppBar: true,
    //     // 设置背景色
    //     backgroundColor: Colors.black,
    //     body: _buildImageView(),
    //   ),
    // );
  }

  // assets 图片视图
  Widget _buildAssetsImageView() {
    return ExtendedImageGesturePageView.builder(
      controller: ExtendedPageController(initialPage: widget.initialIndex),
      itemCount: widget.items?.length ?? 0,
      onPageChanged: (value) => {
        setState(() {
          _currentPage = value + 1;
        })
      },
      itemBuilder: (BuildContext context, int index) {
        final AssetEntity item = widget.items![index];

        Widget image = ExtendedImage(
          image: AssetEntityImageProvider(
            item,
            isOriginal: true,
          ),
          // 根据内容缩放
          fit: BoxFit.contain,
          // 只是手势的模式
          mode: ExtendedImageMode.gesture,
          initGestureConfigHandler: ((state) {
            return GestureConfig(
              // 是否使用 ExtendedImageGesturePageView 展示图片
              inPageView: true,
              initialScale: 1.0,
              //you can cache gesture state even though page view page change.
              //remember call clearGestureDetailsCache() method at the right time.(for example,this page dispose)
              cacheGesture: false,
            );
          }),
        );
        image = Container(
          child: image,
          padding: EdgeInsets.all(5.0),
        );
        return image;
      },
    );
  }

  // URL 图片视图
  Widget _buildUrlsImageView() {
    return ExtendedImageGesturePageView.builder(
      controller: ExtendedPageController(
        initialPage: widget.initialIndex,
      ),
      itemCount: widget.imageUrls?.length ?? 0,
      onPageChanged: (value) => {
        setState(() {
          _currentPage = value + 1;
        })
      },
      itemBuilder: (BuildContext context, int index) {
        final String src = widget.imageUrls![index];
        return ExtendedImage(
          image: ExtendedNetworkImageProvider(
              DuTools.imageUrlFormat(src, width: 700)),
          fit: BoxFit.contain,
          mode: ExtendedImageMode.gesture,
          initGestureConfigHandler: (state) {
            return GestureConfig(
              minScale: 0.9,
              animationMinScale: 0.7,
              maxScale: 3.0,
              animationMaxScale: 3.5,
              speed: 1.0,
              inertialSpeed: 100.0,
              initialScale: 1.0,
              inPageView: true,
            );
          },
        );
      },
    );
  }

// 初始化加载视频
  Future<void> _onLoadVideo() async {
    if (widget.timelineModel?.postType != "2") {
      return Future.value();
    }

    try {
      // video_player 初始化
      _videoController = VideoPlayerController.networkUrl(
          Uri.parse(widget.timelineModel?.video?.url ?? ""));

      // 尝试打开给定的 [dataSource] 并加载有关视频的元数据
      await _videoController?.initialize();

      // chewie 初始化
      _chewieController = ChewieController(
          videoPlayerController: _videoController!,
          autoPlay: true,
          looping: false,
          autoInitialize: true,
          showOptions: false,
          // 用于 IOS 控件的颜色，默认清空下，ios播放器使用 从原始 IOS11 设计中采用的颜色
          cupertinoProgressColors: ChewieProgressColors(
            playedColor: accentColor,
          ),
          // 用于 material 进度条的颜色，默认情况下，材料播放器使用主图中的颜色。
          materialProgressColors: ChewieProgressColors(
            playedColor: accentColor,
          ),
          // 定义是否显示播放速度控件
          allowPlaybackSpeedChanging: false,
          // 定义进入全屏时允许的设备方向集
          deviceOrientationsOnEnterFullScreen: [
            DeviceOrientation.landscapeLeft,
            DeviceOrientation.landscapeRight,
            DeviceOrientation.portraitUp,
          ],
          // 定义退出全屏后允许的设备方向
          deviceOrientationsAfterFullScreen: [
            DeviceOrientation.portraitUp,
          ],

          // 占位组件
          placeholder: _videoController?.value.isInitialized != true
              ? Image.network(
                  DuTools.imageUrlFormat(
                    widget.timelineModel?.video?.cover ?? "",
                    width: 400,
                  ),
                  fit: BoxFit.cover,
                )
              : null);
    } catch (e) {
      DuToast.show('video url load error.');
    } finally {
      if (mounted) setState(() {});
    }
  }

// 视频视图
  Widget _buildVideoView() {
    return Center(
      child: AspectRatio(
        aspectRatio: 16 / 9,
        child: Container(
          color: Colors.grey[100],
          child: Container(
              decoration: BoxDecoration(color: Colors.black),
              child: _chewieController == null
                  ? Text(
                      '视频载入中 loading...',
                      style: textStyleDetail,
                      textAlign: TextAlign.center,
                    )
                  : Chewie(controller: _chewieController!)),
        ),
      ),
    );
  }

  // 导航栏 - 选相册
  AppBarWidget _buildPublishNav(int pages) {
    return AppBarWidget(
      isAnimated: true,
      isShow: _isShowAppBar,
      title: Text(
        "${_currentPage}/${pages}",
        style: TextStyle(
          color: Colors.white,
          fontSize: 16,
        ),
      ),
      leading: GestureDetector(
        onTap: () {
          Navigator.pop(context);
        },
        child: const Icon(
          Icons.arrow_back_ios_outlined,
          color: Colors.white,
        ),
      ),
      actions: [
        Padding(
          padding: const EdgeInsets.only(
            right: pagePadding,
          ),
          child: ElevatedButton(
            onPressed: () {},
            child: Text('发布'),
          ),
        ),
      ],
    );
  }

// 导航栏 - 图片 url 列表
  AppBarWidget _buildPreviewNav(int pages) {
    return AppBarWidget(
      isAnimated: true,
      isShow: _isShowAppBar,
      title: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          // 日期
          Text(
            widget.timelineModel?.publishDate ?? "",
            style: const TextStyle(
              color: Colors.white,
              fontSize: 16,
            ),
          ),

          // 页码页数
          Text(
            "${_currentPage}/${pages}",
            style: TextStyle(
              color: Colors.white,
              fontSize: 12,
            ),
          )
        ],
      ),
      leading: GestureDetector(
        onTap: () {
          Navigator.pop(context);
        },
        child: const Icon(
          Icons.arrow_back_ios_outlined,
          color: Colors.white,
        ),
      ),
      actions: [
        GestureDetector(
          onTap: () {
            // 导航压入新界面
            Navigator.push(context, MaterialPageRoute(builder: (context) {
              return Scaffold(
                appBar: AppBar(
                  title: const Text('新界面'),
                ),
                body: const Center(
                  child: Text('新界面'),
                ),
              );
            }));
          },
          child: Padding(
            padding: const EdgeInsets.only(
              right: pagePadding,
            ),
            child: Icon(
              Icons.more_horiz_outlined,
              color: Colors.white,
            ),
          ),
        ),
      ],
    );
  }

  // 动态栏
  Widget? _buildTimelineBar(bool isShow) {
    TimelineModel? timeline = widget.timelineModel;
    int likesCount = timeline?.likes?.length ?? 0;
    int commentsCount = timeline?.comments?.length ?? 0;

    if (isShow == false || timeline == null) {
      return null;
    }

    return Column(
      mainAxisSize: MainAxisSize.min,
      children: [
        // 内容
        Padding(
          padding: EdgeInsets.all(spacing),
          child: Text(
            timeline.content ?? "",
            style: textStyleDetail,
          ),
        ),

        // 点赞数
        Container(
          color: Colors.black,
          padding: const EdgeInsets.only(
            left: spacing,
            right: spacing,
            top: spacing,
            bottom: spacing * 2,
          ),
          child: Row(
            children: [
              // like 图标
              if (likesCount > 0)
                const Icon(
                  Icons.favorite_border_outlined,
                  size: 24,
                  color: Colors.white,
                ),

              const SpaceHorizontalWidget(
                space: 5,
              ),

              // like 数量
              if (likesCount > 0)
                Text(
                  "${likesCount}",
                  style: textStyleDetail,
                ),
              const SpaceHorizontalWidget(
                space: 5,
              ),

              // 评论图标
              if (commentsCount > 0)
                const Icon(
                  Icons.chat_bubble_outline,
                  size: 24,
                  color: Colors.white,
                ),
              const SpaceHorizontalWidget(
                space: 5,
              ),

              // 评论 文字
              if (commentsCount > 0)
                Text(
                  "评论${commentsCount}",
                  style: textStyleDetail,
                ),
              const Spacer(),

              // 详情按钮
              GestureDetector(
                onTap: () {},
                child: Text(
                  "详情 >",
                  style: textStyleDetail,
                ),
              ),
            ],
          ),
        ),
      ],
    );
  }
}
